package com.zdp.filesync.rsync.config;

import com.zdp.filesync.monitor.config.FileMonitorInfo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

/**
 * 服务端 暂时没有支持 window的命令
 */
@Data
@Builder
@AllArgsConstructor
public class RsyncConfig {

    private String commentName;

    private String comment;

    private String path;

    private String other;

    private String readOnly = "no";
    private String authUser;
    private String secretsFile;

    private String configPath;

    // 要删除的行数
    private int count  = 6;

    public static RsyncConfig buildRsyncConfig(RsyncServerConfig rsyncServerConfig,
                                               FileMonitorInfo fileMonitorInfo){
        return RsyncConfig.builder()
                .configPath(rsyncServerConfig.getConfigPath())
                .comment(fileMonitorInfo.getCommentName())
                .commentName(fileMonitorInfo.getCommentName())
                .path(fileMonitorInfo.getPath())
                .authUser(rsyncServerConfig.getUserName())
                .secretsFile(rsyncServerConfig.getPwdPath())
                .readOnly(rsyncServerConfig.getReadOnly())
                .other("ignore errors")
                .build();
    }

    public String buildAddConfig(){
        StringBuilder str = new StringBuilder();
        str.append("[").append(commentName).append("]\n")
                .append("comment = ").append(comment).append("\n")
                .append("path = ").append(path).append("\n")
                .append(other).append("\n")
                .append("read only = ").append(readOnly).append("\n")
                .append("auth users = ").append(authUser).append("\n")
                .append("secrets file = ").append(secretsFile).append("\n");

        return str.toString();
    }

    public String buildAddConfigBash(){
        StringBuilder str = new StringBuilder();
        str.append("echo -e '").append(buildAddConfig())
                .append("' >> ").append(configPath);
        return str.toString();
    }

    // 需要添加路径
    public String buildDelConfigBash(){
        StringBuilder str = new StringBuilder();
        str.append("sed -i '/\\[")
                .append(commentName).append("\\],+")
                .append(count).append("d' ")
                .append(configPath);

        return str.toString();
    }

}
